package com.xmall.order.service.impl.platform;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmall.order.define.dict.AfterSaleStatusEnum;
import com.xmall.define.dict.OrderStatusEnum;
import com.xmall.order.define.dict.RefundStatusEnum;
import com.xmall.order.define.dict.RefundTypeEnum;
import com.xmall.order.define.dto.OrderDtoWithCascade;
import com.xmall.order.define.dto.platform.OrderDtoForFront;
import com.xmall.order.define.dto.platform.OrderItemDtoForFront;
import com.xmall.order.define.dto.platform.OrderNumStatistics;
import com.xmall.order.define.dto.platform.OrderOperateBtnForFront;
import com.xmall.order.define.dto.OrderQueryParams;
import com.xmall.order.define.request.query.FrontOrderListPageQueryRequest;
import com.xmall.order.entity.Order;
import com.xmall.order.entity.OrderRefund;
import com.xmall.order.service.IOrderRefundService;
import com.xmall.order.service.IOrderService;
import com.xmall.order.service.platform.IOrderFrontService;
import com.xmall.order.utils.ConvertUtils;
import com.xmall.utils.XmallUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderFrontServiceImpl implements IOrderFrontService {

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderRefundService orderRefundService;

    /**
     * 详情
     */
    @Override
    public OrderDtoForFront info(Long id) {
        OrderDtoForFront orderDto = ConvertUtils.OrderModule.INSTANCE.toFront(orderService.infoWithCascade(id));

        this.setOrderItemListForFront(orderDto);
        this.setOrderOperateBtnState(orderDto);
        this.setOrderItemOperateBtnState(orderDto);
        return orderDto;
    }

    /**
     * 详情
     */
    @Override
    public OrderDtoForFront infoByOrderSn(String orderSn) {
        Order entity = orderService.getOne(new QueryWrapper<Order>().eq("order_sn", orderSn));
        XmallUtils.notNull(entity);
        return this.info(entity.getId());
    }

    /**
     * 分页列表
     */
    @Override
    public Page<OrderDtoForFront> listPage(FrontOrderListPageQueryRequest request) {
        Page<OrderDtoForFront> result = new Page<>();

        OrderQueryParams query = ConvertUtils.OrderModule.INSTANCE.toQueryParams(request);
        query.setStatusList(request.getStatusList());

        Page<OrderDtoWithCascade> page = orderService.listPageWithCascade(new Page(request.getPage(), request.getPageSize()), query);
        BeanUtils.copyProperties(page, result);
        result.setRecords(ConvertUtils.OrderModule.INSTANCE.listToFront(page.getRecords()));

        // 设置订单子项
        result.getRecords().forEach(orderDto -> this.setOrderItemListForFront(orderDto));
        // 设置订单操作按钮
        result.getRecords().forEach(orderDto -> this.setOrderOperateBtnState(orderDto));
        // 设置订单子项操作按钮
        result.getRecords().forEach(orderDto -> this.setOrderItemOperateBtnState(orderDto));
        return result;
    }

    /**
     * 不同状态订单数量
     */
    @Override
    public OrderNumStatistics orderNumStatistics(Long memberId) {
        OrderNumStatistics result = new OrderNumStatistics();
        result.setWaitPay(orderService.count(new QueryWrapper<Order>().eq("order_status", OrderStatusEnum.WAIT_PAY.getStatus())));
        result.setWaitConsign(orderService.count(new QueryWrapper<Order>().eq("order_status", OrderStatusEnum.WAIT_CONSIGN.getStatus())));
        result.setWaitReceive(orderService.count(new QueryWrapper<Order>().eq("order_status", OrderStatusEnum.WAIT_RECEIVE.getStatus())));
        return result;
    }

    /**
     * 设置订单子项
     */
    private void setOrderItemListForFront(OrderDtoForFront orderDto) {
        List<OrderItemDtoForFront> orderItems = orderDto.getOrderItems().stream().map(orderItemDto -> ConvertUtils.OrderItemModule.INSTANCE.toFront(orderItemDto)).collect(Collectors.toList());
        orderDto.setOrderItemsForFront(orderItems);
    }

    /**
     * 设置订单操作按钮
     */
    private void setOrderOperateBtnState(OrderDtoForFront orderDto) {
        Integer orderStatus = orderDto.getOrderStatus();
        OrderOperateBtnForFront operateBtn = new OrderOperateBtnForFront();
        // 删除订单按钮
        operateBtn.setShowDeleteOrderBtn(OrderStatusEnum.WAIT_CONSIGN.getStatus() != orderStatus && OrderStatusEnum.WAIT_RECEIVE.getStatus() == orderStatus);
        // 查看物流按钮
        operateBtn.setShowExpressBtn(OrderStatusEnum.WAIT_RECEIVE.getStatus() == orderStatus);
        // 去支付按钮
        operateBtn.setShowPayBtn(OrderStatusEnum.WAIT_PAY.getStatus() == orderStatus);
        // 确认收货按钮
        operateBtn.setShowTakeDeliveryBtn(OrderStatusEnum.WAIT_RECEIVE.getStatus() == orderStatus);
        // 售前申请退款按钮
        operateBtn.setShowApplyRefundBtn(OrderStatusEnum.WAIT_CONSIGN.getStatus() == orderStatus && AfterSaleStatusEnum.VALID.getStatus() == orderDto.getAfterSaleStatus());
        // 售后申请退款按钮
        operateBtn.setShowApplyReturnBtn((OrderStatusEnum.WAIT_RECEIVE.getStatus() == orderStatus ||
                OrderStatusEnum.FINISHED.getStatus() == orderStatus)
                && AfterSaleStatusEnum.VALID.getStatus() == orderDto.getAfterSaleStatus());
        // 售后发货按钮
        OrderRefund approveRefund = orderRefundService.getOne(new QueryWrapper<OrderRefund>()
                .eq("order_id", orderDto.getId())
                .isNull("order_item_id")
                .eq("refund_status", RefundStatusEnum.APPROVE.getStatus()));
        operateBtn.setShowReturnDeliveryBtn(null != approveRefund
                && (RefundTypeEnum.RETURN.getType() == approveRefund.getRefundType()
                || RefundTypeEnum.REPLACE.getType() == approveRefund.getRefundType()));
        orderDto.setOperateBtn(operateBtn);
    }

    /**
     * 设置订单子项操作按钮
     */
    private void setOrderItemOperateBtnState(OrderDtoForFront orderDto) {
        Integer orderStatus = orderDto.getOrderStatus();
        orderDto.getOrderItemsForFront().forEach(orderItem -> {
            // 售后状态
            orderItem.setRefundStatusName(orderRefundService.getOrderItemRefundStatusName(orderItem.getOrderId(), orderItem.getId()));
            // 售后申请退款按钮
            orderItem.setShowApplyReturnBtn((OrderStatusEnum.WAIT_RECEIVE.getStatus() == orderStatus ||
                OrderStatusEnum.FINISHED.getStatus() == orderStatus ||
                OrderStatusEnum.PART_REFUND.getStatus() == orderStatus)
                && AfterSaleStatusEnum.VALID.getStatus() == orderItem.getAfterSaleStatus());
            // 售后发货按钮
            OrderRefund approveRefund = orderRefundService.getOne(new QueryWrapper<OrderRefund>()
                    .eq("order_id", orderItem.getOrderId())
                    .eq("order_item_id", orderItem.getId())
                    .eq("refund_status", RefundStatusEnum.APPROVE.getStatus()));
            orderItem.setShowReturnDeliveryBtn(null != approveRefund
                    && (RefundTypeEnum.RETURN.getType() == approveRefund.getRefundType()
                    || RefundTypeEnum.REPLACE.getType() == approveRefund.getRefundType()));
        });
    }

}
